﻿/* Project: Side Scrolling Shooter
 * The missile fired by the player.
 * Detects if it has collided with an enemy.
 * Last Update: 4/12/11,11:16PM
 */

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace TheFifthSpace
{
    public class PlayerMissile : DrawableGameComponent
    {
        public float posX, posY;
        public Texture2D sprite;
        //private SpriteBatch spriteBatch;
        private Vector2 offset;
        private float speed;

        public Vector2 Position
        {
            get
            {
                return new Vector2(posX, posY);
            }
            set
            {
                posX = value.X;
                posY = value.Y;
            }
        }

        // CONSTRUCTOR
        public PlayerMissile(Game g, Vector2 p)
            : base(g)
        {
            Game.Components.Add(this);
            Position = p;
            speed = 450f;
        }

        // LOAD CONTENT
        protected override void LoadContent()
        {
            sprite = MainGame.playerMissileSprite;
            //spriteBatch = MainGame.spriteBatch;
            offset = new Vector2(sprite.Width / 2, sprite.Height / 2);
        }

        // DRAW
        public override void Draw(GameTime gameTime)
        {
            MainGame.spriteBatch.Begin();
            MainGame.spriteBatch.Draw(sprite, Position - offset, Color.White);
            MainGame.spriteBatch.End();
        }

        public override void Update(GameTime gameTime)
        {
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            posX += (dt * speed);
        }

        public virtual void Die()
        {
            // Pre-death actions
            MainGame.PlayerMissiles.Remove(this);
            
            Game.Components.Remove(this);
        }

        // Check to see if missile has hit enemy
        public bool HitsEnemy(Enemy e)
        {
            Rectangle myRect = new Rectangle(
                (int)(posX - offset.X), (int)(posY - offset.Y),
                sprite.Width, sprite.Height);
            Rectangle enemyRect = new Rectangle(
                (int)(e.Position.X - e.Offset.X), (int)(e.Position.Y - e.Offset.Y),
                e.sprite.Width, e.sprite.Height);
            if (myRect.Intersects(enemyRect)) return true;
            else return false;
        }
    }
}